package ar.com.hc.view.mainwindow.menu;

import java.awt.GridLayout;
import java.awt.MenuComponent;
import java.io.IOException;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import ar.com.hc.utils.HCI18n;

public class HCMenuBar extends JMenuBar {

	private static final String MENU_FILE = "resources/menu.xml";

	private Document dom;

	public HCMenuBar() {
		super();
		setLayout(new GridLayout(0, 1));
		readModel();

	}

	private void readModel() {
		DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		try {
			builder = f.newDocumentBuilder();
			dom = builder.parse(MENU_FILE);
			parseDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void parseDocument() {
		Element docEle = dom.getDocumentElement();
		parseMenuElement(docEle, null);

	}

	private void parseMenuElement(Element root, JMenu parent) {
		System.out.println(root);
		NodeList menuNl = root.getElementsByTagName("menu");
		if (menuNl != null && menuNl.getLength() > 0) {
			for (int i = 0; i < menuNl.getLength(); i++) {
				Element el = (Element) menuNl.item(i);
				JMenu menu = createMenuComponent(el);
				addMenuElement(parent, menu);
				parseMenuElement(el, menu);
			}
		}
		NodeList menuItemNl = root.getElementsByTagName("menuItem");
		if (menuItemNl != null && menuItemNl.getLength() > 0) {
			for (int i = 0; i < menuItemNl.getLength(); i++) {
				Element el = (Element) menuItemNl.item(i);
				JMenuItem menuItem = createMenuItemComponent(el);
				addMenuElement(parent, menuItem);

			}
		}

	}

	private void addMenuElement(JMenuItem parent, JMenuItem child) {
		if (parent == null) {
			this.add(child);
		} else {
			parent.add(child);
		}
	}

	private JMenuItem createMenuItemComponent(Element el) {
		JMenuItem item = new JMenuItem();
		item.setText(HCI18n.getInstance().getMessage(el.getAttribute("text")));
		return item;
	}

	private JMenu createMenuComponent(Element el) {
		JMenu menu = new JMenu();
		menu.setText(HCI18n.getInstance().getMessage(el.getAttribute("text")));
		return menu;
	}

}
